<?php
namespace Home\Controller;
use Think\Controller;

// 可能长时间执行，禁用最大执行时间
set_time_limit(0);


class AjaxController extends Controller {
    public function index(){
    }

    public function ajax_scan(){
        if(session('?username')){
            $post_data = get_json();
            if(isset($post_data['target']) && preg_match("/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is", $post_data['target'])){
                $post_data['target'] = rtrim($post_data['target'], '/');
                $result = array();

                // 先获取http请求头信息
                $ret = http_request($post_data['target'], 'GET', true);
                $result['header'] = $ret['header'];

                // 新增扫描结果数据
                $result_id = M('results')->data(array('target'=>$post_data['target'], 'progress'=>'0%', 'header'=>serialize($result['header']), 'time'=>time()))->add();
                $total = M('fingers')->count();

                if($result_id > 0){
                    $count = 0; //已经检测的指纹数量

                    // 先查询所有指纹的uri，并去重
                    $uris = M('fingers')->Distinct(true)->field('uri, method, content_type, post_data, cookies')->select();
                    
                    // 循环执行HTTP请求，获取返回值
                    $res_finger = array();
                    foreach($uris as $uri){
                        $res = http_request(
                            $post_data['target'].$uri['uri'], 
                            ($uri['method'] == 2 ? 'POST' : 'GET'), 
                            false, 
                            $uri['cookies'], 
                            $uri['post_data'], 
                            $uri['content_type']);
                        
                        // 查找该uri所有指纹进行匹配
                        $fingers = M('fingers')
                            ->field('id, app_name, app_version, app_script, match_type, signature ,uri')
                            ->where(array(
                                        'uri'=> $uri['uri'],
                                        'method'=>$uri['method'], 
                                        'content_type'=>$uri['content_type'], 
                                        'post_data'=>$uri['post_data']))
                            ->select();

                        foreach($fingers as $finger){
                            //var_dump($finger['match_type'].'|'.$finger['signature'].'|'.$result['body']);
                            if(finger_match($finger['match_type'], $finger['signature'], $res['code'], $res['body'])){
                                array_push($res_finger, array(
                                    'id'=>$finger['id'], 
                                    'app_name'=>$finger['app_name'], 
                                    'app_version'=>$finger['app_version'], 
                                    'app_script'=>$finger['app_script']));
                                M('scan_logs')->data(array('finger_id'=>$finger['id'], 'result'=> 1, 'result_id'=>$result_id, 'time'=>time()))->add();
                            }else{
                                M('scan_logs')->data(array('finger_id'=>$finger['id'], 'result'=> 0, 'result_id'=>$result_id, 'time'=>time()))->add();
                            }
                            $count ++;
                            // 更新检测进度
                            round($count / $total * 100, 1);
                            M('results')->where(array('id'=>$result_id))->save(array('progress'=> (string)round($count / $total * 100, 1).'%'));
                        }
                    }
                    $result['finger'] = $res_finger;
                    
                    print_json(array('error' => 0, 'data'=>$result));
                }else{
                    print_json(array('error' => 3, 'msg'=>'添加检测结果错误'));
                }
            }else{
                print_json(array('error' => 1, 'msg'=>'参数错误或URL不合法'));
            }
        }else{
            print_json(array('error' => 2, 'msg'=>'没有权限，请登录后使用'));
        }
    }

    public function ajax_test(){
        if(session('?username')){
            $post_data = get_json();
            //var_dump($post_data);
            if(!empty('finger_match_type') && !empty('finger_uri') && !empty('finger_method')
                && !empty('finger_post_data') && !empty('finger_content_type') && !empty('finger_signature')){
                if(preg_match("/http[s]?:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is", $post_data['target'])){
                    $post_data['target'] = rtrim($post_data['target'], '/');
                     // 执行http请求，获取返回值
                    $result = http_request(
                        $post_data['target'].$post_data['finger_uri'], 
                        ($post_data['finger_method'] == 2 ? 'POST' : 'GET'), 
                        false, 
                        $post_data['finger_cookies'], 
                        $post_data['finger_post_data'], 
                        $post_data['finger_content_type']);
                    //var_dump($content);
                    if(finger_match($post_data['finger_match_type'], $post_data['finger_signature'], $result['code'], $result['body'])){
                        if(APP_DEBUG){
                            print_json(array('error' => 0, 'msg'=>'测试通过，该指纹有效', 'data'=>$result));
                        }else{
                            print_json(array('error' => 0, 'msg'=>'测试通过，该指纹有效'));
                        }
                    }else{
                        if(APP_DEBUG){
                            print_json(array('error' => 3, 'msg'=>'检测不通过，请检查URL和指纹配置是否正确', 'data'=>$result));
                        }else{
                            print_json(array('error' => 3, 'msg'=>'检测不通过，请检查URL和指纹配置是否正确'));
                        }
                    }
                }else{
                    print_json(array('error' => 1, 'msg'=>'URL不合法，请勿在网址后输入/'));
                }
            }else{
                print_json(array('error' => 1, 'msg'=>'参数错误'));
            }
        }else{
            print_json(array('error' => 2, 'msg'=>'没有权限，请登录后使用'));
        }
    }

    public function ajax_add_finger(){
        if(session('?username')){
            $post_data = get_json();
            if(!empty($post_data['app_name']) && !empty($post_data['finger_match_type']) && !empty($post_data['finger_uri']) && !empty($post_data['finger_method'])){
                $data['app_name'] = $post_data['app_name'];
                $data['app_type'] = $post_data['app_type'];
                $data['app_version'] = $post_data['app_version'];
                $data['app_script'] = $post_data['app_script'];
                $data['method'] = $post_data['finger_method'];
                $data['content_type'] = $post_data['finger_content_type'];
                $data['post_data'] = $post_data['finger_post_data'];
                $data['match_type'] = $post_data['finger_match_type'];
                $data['cookies'] = $post_data['finger_cookies'];
                $data['uri'] = $post_data['finger_uri'];
                $data['signature'] = $post_data['finger_signature'];
                $data['description'] = $post_data['finger_desc'];
                (M('fingers')->data($data)->add() == false) ? print_json(array('error' => 2, 'msg'=>'添加指纹错误')) : print_json(array('error' => 0, 'msg'=>'添加成功'));
            }else{
                print_json(array('error' => 1, 'msg'=>'参数错误'));
            }
        }else{
            print_json(array('error' => 2, 'msg'=>'没有权限，请登录后使用'));
        }
    }

    public function ajax_del_finger(){
        if(session('?username')){
            $post_data = get_json();
            if(!empty($post_data['id'])){
                (M('fingers')->where(array('id'=>$post_data['id']))->delete() == false) ? print_json(array('error' => 2, 'msg'=>'删除指纹错误')) : print_json(array('error' => 0, 'msg'=>'删除成功'));
            }else{
                print_json(array('error' => 1, 'msg'=>'参数错误'));
            }
        }else{
            print_json(array('error' => 2, 'msg'=>'没有权限，请登录后使用'));
        }
    }

    public function ajax_list_finger(){
        if(session('?username')){
            $page = I('get.page');$limit = I('get.limit');$keyword=I('get.keyword');
            if($page > 0 && $limit > 0){
                $count = M('fingers')->count();
                $result = M('fingers')
                        ->field('id, app_name, app_version, method, uri, signature')
                        ->limit(($page - 1) * $limit, $limit)
                        ->where(array('app_name' => array('LIKE', '%' . $keyword . '%')))
                        ->select();
                print_json(array('code' => 0, 'msg'=>'', 'count'=>$count, 'data'=>$result));
            }else{
                print_json(array('code' => 1, 'msg'=>'参数错误'));
            }
        }else{
            print_json(array('code' => 2, 'msg'=>'没有权限，请登录后使用'));
        }
    }

    public function ajax_search_finger(){
        if(session('?username')){
            $page = I('get.page');$limit = I('get.limit');
            if($page > 0 && $limit > 0){
                $count = M('fingers')->count();
                $result = M('fingers')->field('id, app_name, app_version, method, uri, signature')->limit(($page - 1) * $limit, $limit)->select();
                print_json(array('code' => 0, 'msg'=>'', 'count'=>$count, 'data'=>$result));
            }else{
                print_json(array('code' => 1, 'msg'=>'参数错误'));
            }
        }else{
            print_json(array('code' => 2, 'msg'=>'没有权限，请登录后使用'));
        }
    }

    public function ajax_scan_log(){
        if(session('?username')){
            $page = I('get.page');$limit = I('get.limit');
            if($page > 0 && $limit > 0){
                $count = M('results')->count();
                $result = M('results')->limit(($page - 1) * $limit, $limit)->select();
                print_json(array('code' => 0, 'msg'=>'', 'count'=>$count, 'data'=>$result));
            }else{
                print_json(array('code' => 1, 'msg'=>'参数错误'));
            }
        }else{
            print_json(array('code' => 2, 'msg'=>'没有权限，请登录后使用'));
        }
    }

}